package com.taldh.algorithm.listnode;

import com.taldh.algorithm.base.ListNode;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author donghaoyuan
 */
public class AddTwoNumbers2 {

    int flow=0;
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        ListNode res1=l1,res2=l2;
        int len1=0,len2=0;
        while(l1!=null){
            len1++;
            l1=l1.next;
        }
        while(l2!=null){
            len2++;
            l2=l2.next;
        }
        ListNode res=len1>len2?add(res1,res2,len1,len2):add(res2,res1,len2,len1);
        if(flow==1) {
            res1=new ListNode(1);
            res1.next=res;
            return res1;
        }
        return res;
    }
    public ListNode add(ListNode l1, ListNode l2,int len1,int len2) {
        int temp;
        if((len1==1)&&(len2==1)){
            temp=l1.val;
            l1.val=(l1.val+l2.val)%10;
            flow=(temp+l2.val)/10;
            return l1;
        }
        if(len1>len2) {
            temp=l1.val;
            l1.next=add(l1.next, l2,len1-1,len2);
            l1.val=(temp+flow)%10;
            flow=(temp+flow)/10;
            return l1;
        }
        l1.next=add(l1.next, l2.next,len1-1,len2-1);
        temp=l1.val;
        l1.val=(temp+flow+l2.val)%10;
        flow=(temp+flow+l2.val)/10;
        return l1;

    }

    @Test
    public void test(){
        Assert.assertTrue(ListNode.isEquals(new ListNode(new int[]{7, 8, 0, 7}),
                addTwoNumbers(new ListNode(new int[]{7, 2, 4, 3}),
                        new ListNode(new int[]{5, 6, 4}))));
    }
}